/****************************************************************************/
/*  File:       ModulesFactory.java                                         */
/*  Author:     F. Georges - fgeorges.org                                   */
/*  Date:       2009-06-21                                                  */
/*  Tags:                                                                   */
/*      Copyright (c) 2009 Florent Georges (see end of file.)               */
/* ------------------------------------------------------------------------ */


package org.expath.pkg.exist;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * Build a list of {@link Module} from a repository's {@code modules.xml} file.
 *
 * @author Florent Georges
 * @date   2009-06-21
 */
public class ModulesFactory
        implements ContentHandler
{
    public ModulesFactory(ExistInstance repo)
    {
        myHome = repo;
    }

    public List<Module> read(File f)
            throws PackageException
    {
        try {
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(this);
            InputSource src = new InputSource(new FileInputStream(f));
            reader.parse(src);
            return myModules;
        }
        catch ( FileNotFoundException ex ) {
            throw new PackageException("modules file not found [" + f + "]", ex);
        }
        catch ( IOException ex ) {
            throw new PackageException("Error reading modules file [" + f + "]", ex);
        }
        catch ( SAXException ex ) {
            throw new PackageException("Error parsing modules file [" + f + "]", ex);
        }
    }

    public void setDocumentLocator(Locator locator)
    {
        // TODO: Should use it to report errors...
    }

    public void startDocument()
            throws SAXException
    {
        // nothing
    }

    public void endDocument()
            throws SAXException
    {
        // nothing
    }

    public void startPrefixMapping(String prefix, String uri)
            throws SAXException
    {
        // nothing
    }

    public void endPrefixMapping(String prefix)
            throws SAXException
    {
        // nothing
    }

    public void startElement(String uri, String local, String qname, Attributes atts)
            throws SAXException
    {
        if ( MOD_NS.equals(uri) ) {
            if ( "modules".equals(local) ) {
                myModules = new ArrayList<Module>();
            }
            else if ( "module".equals(local) ) {
                myCurrModule = new Module();
                myModules.add(myCurrModule);
                String ver = atts.getValue("", "version");
                if ( ver == null ) {
                    throw new SAXException("pkg:module/@version is not there");
                }
                myCurrModule.setVersion(ver);
                String name = atts.getValue("", "name");
                if ( name == null ) {
                    throw new SAXException("pkg:module/@name is not there");
                }
                myCurrModule.setName(name);
                String jar = atts.getValue("", "jar");
                if ( jar == null ) {
                    throw new SAXException("pkg:module/@jar is not there");
                }
                myCurrModule.setJar(new File(myHome.getHomeDir(), jar));
            }
            else if ( "title".equals(local) ) {
                myBuffer = new StringBuilder();
            }
            else {
                throw new SAXException("Unknown element: {" + uri + "}" + local);
            }
        }
        else {
            throw new SAXException("Unknown element: {" + uri + "}" + local);
        }
    }

    public void endElement(String uri, String local, String qname)
            throws SAXException
    {
        // ns has already been checked in startElement()
        if ( "module".equals(local) ) {
            myCurrModule = null;
        }
        else if ( "title".equals(local) ) {
            myCurrModule.setTitle(myBuffer.toString());
            myBuffer = null;
        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException
    {
        // TODO: Check if there is any non-whitespace characters if == null.
        if ( myBuffer != null ) {
            myBuffer.append(ch, start, length);
        }
    }

    public void ignorableWhitespace(char[] ch, int start, int length)
            throws SAXException
    {
        // nothing
    }

    public void processingInstruction(String target, String data)
            throws SAXException
    {
        // nothing
    }

    public void skippedEntity(String name)
            throws SAXException
    {
        throw new SAXException("Unknown entity: " + name);
    }

    private ExistInstance myHome;
    private List<Module>  myModules;
    private Module        myCurrModule;
    private StringBuilder myBuffer;
    private static final String MOD_NS = "http://expath.org/mod/expath-pkg/modules";
}


/* ------------------------------------------------------------------------ */
/*  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS COMMENT.               */
/*                                                                          */
/*  The contents of this file are subject to the Mozilla Public License     */
/*  Version 1.0 (the "License"); you may not use this file except in        */
/*  compliance with the License. You may obtain a copy of the License at    */
/*  http://www.mozilla.org/MPL/.                                            */
/*                                                                          */
/*  Software distributed under the License is distributed on an "AS IS"     */
/*  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See    */
/*  the License for the specific language governing rights and limitations  */
/*  under the License.                                                      */
/*                                                                          */
/*  The Original Code is: all this file.                                    */
/*                                                                          */
/*  The Initial Developer of the Original Code is Florent Georges.          */
/*                                                                          */
/*  Contributor(s): none.                                                   */
/* ------------------------------------------------------------------------ */
